#!/usr/bin/python

import os
import sys
import shutil
import re
import os.path
from os.path import join

# v8 dir
_v8_dir = None
# v8 dir end

# dirs -- generated from _v8_dir in set_v8_dir
_src_dir = None
_write_dir = None
_bak_dir = None
_test_dir = None

# NOTE: in prod version get_src_path and get_write_path will return the same dir

# files to backup
_files = ["SConscript", "json-delay.js", "runtime.h", "runtime.cc", "prettyprinter.cc"]

# string constants
BACKUP_DIR_NAME = "zbak"
TEST_DIR_NAME = "ztest"

def check_is_v8_dir(v8_dir):
    license_filename = join(v8_dir, "LICENSE")
    if not os.path.exists(license_filename):
        print "Error: Not a V8 Directory: %s - V8 LICENSE file not found" % (v8_dir)
        sys.exit()
    f_license = open(license_filename)
    s_license = f_license.read()
    f_license.close()
    if s_license.find("V8") == -1:
        print "Error: Not a V8 Directory: %s - V8 LICENSE file does not contain 'V8' string" % (v8_dir)
        sys.exit()
    

def set_v8_dir(v8_dir):
    # define the module globals which will be updated
    global _src_dir
    global _v8_dir
    global _write_dir
    global _bak_dir
    global _test_dir
    
    # set the module var to the absolute path of v8_dir
    _v8_dir = os.path.abspath(v8_dir)
    
    # set the other module vars which use the v8 dir as the root
    _src_dir = join(_v8_dir, "src")
    _write_dir = _src_dir
    _bak_dir = join(_v8_dir, BACKUP_DIR_NAME)
    _test_dir = join(_v8_dir, TEST_DIR_NAME)
    
    # sanity check on dirs
    if not os.path.isdir(_v8_dir):
        print "Error: V8 Directory '%s' does not exist" % (_v8_dir)
        exit()

    check_is_v8_dir(_v8_dir) # will exit if not a v8 dir

    if not os.path.isdir(_src_dir):
        print "Error: V8 Source Directory '%s' does not exist" % (_src_dir)
        exit()
        
    if not os.path.isdir(_write_dir):
        print "Error: Write Directory '%s' does not exist" % (_write_dir)
        exit()
       
    # print dir settings to stdout
    print "V8 directory is: %s" % (_v8_dir)
    print "V8 src directory is: %s" % (_src_dir)
    print "Backup dir for updated src files: %s" % (_bak_dir)
    #print "Dir for tests: %s" % (_test_dir)


def get_src_path(s_file):
    return join(_src_dir, s_file)


def get_read_path(s_file):
    """ the build scripts 'read' the files to be changed from bak dir"""
    return join(_bak_dir, s_file)


def get_write_path(s_file):
    return join(_write_dir, s_file)


def copy_file_to_bak(s_filename):
    s_file = get_src_path(s_filename)
    if not os.access(s_file, os.W_OK): 
        sys.exit("Cannot copy WRITEABLE file " + s_filename + " from src to bak dir")
        
    # copy file from src dir to bak dir. Keep the creation date etc via copy2
    shutil.copy2(s_file, _bak_dir)
    

def backup_files():
    """ Create a 'backup' dir and copy the files that will
    be updated to it. If the backup dir exists assume the files
    and have been copied and the script is being rerun.
    """

    #if os.access(_bak_dir, os.F_OK):
    if os.path.isdir(_bak_dir):
        # bak dir exists so return
        print "--- Back up directory exists"
        return
    """    
    # check that the token.h etc files have not been updated already
    # - can happen if the bak dir is deleted and build script rerun
    f_token_h = open(get_src_path("token.h"))
    s_token_h = f_token_h.read()
    f_token_h.close()
    if s_token_h.find("Z:") != -1:
        sys.exit("Error: Token.h file in src dir has been updated for zed - should not be copied to backup dir")
    """   

    # create the back dir
    try:
        os.mkdir(_bak_dir)
    except:
        print "Error: Unable to create backup dir:" + _bak_dir
        exit()
        

    for f in _files:
        copy_file_to_bak(f)
        
    print "--- Back up directory created and files copied"

"""
def copy_zparser_file():
    s_zparser_file = "zparser.cc"
    # check if file has been copied to 'src' dir already
    if os.path.isfile(get_src_path(s_zparser_file)):
        print "--- Copy of %s file exists in src dir" % (s_zparser_file)
        # check if the copy in src has been modified
        if os.path.getmtime(s_zparser_file) != os.path.getmtime(get_src_path(s_zparser_file)):
            # give a warning message - the developer may want to copy the zparser.cc file 
            # to be copied back to this build dir 
            print "*** MESSAGE ***"
            print "    The Copy of the '%s' file in '%s' has been modified." % (s_zparser_file, _src_dir)
            print "    The original of the %s file in '%s' should be updated with any modifications you wish to keep." % (s_zparser_file, os.path.abspath("."))
            print "*** MESSAGE END ***"
    else:
        print "--- Copy %s file to src dir" % (s_zparser_file)
        shutil.copy2("zparser.cc", _src_dir)
"""
    
def copy_test_dir():
    # check that the zed test dir exist as a subdir of the build code dir
    if not os.path.isdir(TEST_DIR_NAME):
        sys.exit("The dir of zed tests '" + TEST_DIR_NAME + "'does not exist")
    
    # copy the test dir if it hasn't already been copied
    if not os.path.exists(_test_dir):
        shutil.copytree(TEST_DIR_NAME, _test_dir)
        print "--- Test dir created"
    else:
        print "--- Test dir exists"


# main
def main():
    print "run backup_files:"
    backup_files()
    

# call main  
if __name__ == "__main__":
    main()



